/**
 * 
 */
package com.ginger.rabbitmq.consumer;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;

/**
 * @Description:RabbitMQ 接收
 * @author 姜锋
 * @date 2019年4月2日 下午5:28:55
 * @version V1.0
 */
@Component
public class RabbitMQReceive {
	private final static Logger logger = LoggerFactory.getLogger(RabbitMQReceive.class);

	@SuppressWarnings("rawtypes")
	@RabbitListener(
			bindings = @QueueBinding(
					value = @Queue(value = "spring_queue1",
					durable = "true"),
					exchange = @Exchange(
							value = "spring_exchange1",
							durable = "true",
							type = "topic",
							ignoreDeclarationExceptions = "true"),
					key = "spring.#"
					)
			)
	@RabbitHandler
	public void onMessage(Message message, Channel channel) throws Exception {
		logger.warn("-----     消费端     -----");
		Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
		logger.warn("消费端收到 message ACK(Long) --> " + deliveryTag);
		logger.warn("消费端收到 message Payload --> " + message.getPayload());
		// 手工ACK
		channel.basicAck(deliveryTag, false);
	}
	@RabbitListener(
			bindings = @QueueBinding(
					value = @Queue(value = "${spring.rabbitmq.lisener.order.queue.name}",
					durable = "${spring.rabbitmq.lisener.order.queue.durable}"),
					exchange = @Exchange(
							value = "${spring.rabbitmq.lisener.order.exchange.name}",
							durable = "${spring.rabbitmq.lisener.order.exchange.durable}",
							type = "${spring.rabbitmq.lisener.order.exchange.type}",
							ignoreDeclarationExceptions = "${spring.rabbitmq.lisener.order.exchange.ignoreDeclarationExceptions}"),
					key = "${spring.rabbitmq.lisener.order.key}"
					)
			)
	@RabbitHandler
	public void onOrderMessage(@Payload com.ginger.rabbitmq.entity.Order order, Channel channel,
			@Headers Map<String, Object> headers) throws Exception {
		logger.warn("-----     消费端-Order     -----");
		logger.warn("消费端收到  Order Id message  --> " + order.getId());
		Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
		logger.warn("消费端收到 message ACK(Long) --> " + deliveryTag);
		// 手工ACK
		channel.basicAck(deliveryTag, false);
	}
}
